<?php
class TbfUpload{
    static $imageExtList = array('jpg','png','gif','jpeg','bmp');
    static $attachExtList = array('png', 'jpg', 'jpeg', 'gif', 'bmp',
    'flv', 'swf', 'mkv', 'avi', 'rm', 'rmvb', 'mpeg', 'mpg', 'ogg',
        'ogv', 'mov', 'wmv', 'mp4', 'webm','mp3', 'wav', 'mid',
    'rar', 'zip', 'tar', 'gz', '7z', 'bz2', 'cab', 'iso',
    'doc', 'docx', 'xls', 'xlsx', 'ppt', 'pptx', 'pdf',
    'txt', 'md', 'xml');
    static function jsonImageUpload(){
        $ret = self::ArrayImageUpload();
        if (!empty($ret['err'])){
            echo json_encode($ret);
        }else{
            echo json_encode(array('err'=>'','data'=>$ret['url']));
        }
    }

    static function hiddenIframeImageUpload(){
        $ret = self::ArrayImageUpload();
        $output = array();
        if (!empty($ret['err'])){
            $output['err'] = $ret['err'];
        }else{
            $output['data'] = $ret['url'];
        }
        echo '<script>var data=';exje($output);echo ';</script>';
    }

    static function ArrayImageUpload(){
        return self::_arrayUploadInner('image',self::$imageExtList);
    }

    static function jsonAttachUpload(){
        $ret = self::_arrayUploadInner('attach',self::$attachExtList);
        if (!empty($ret['err'])){
            echo json_encode($ret);
        }else{
            echo json_encode(array('err'=>'','data'=>$ret['url']));
        }
    }
    static function _arrayUploadInner($name,$extArray){
        //文件路径没有结尾的/
        $saveBasePath = TbfConfig::$UploadPath.'/'.$name;
        if (empty($_FILES['file']['tmp_name'])){
            return array('err'=>'upload file not found');
        }
        @mkdir($saveBasePath);
        $ext = TbfFile::getExtLower($_FILES['file']['name']);
        if (!in_array($ext,$extArray)){
            return array('err'=>'ext not allow.');
        }
        $fileName = md5_file($_FILES['file']['tmp_name']).'.'.$ext;
        $ret = move_uploaded_file($_FILES['file']['tmp_name'],$saveBasePath.'/'.$fileName);
        if (!$ret){
            return array('err'=>'move fail');
        }
        return array('err'=>'','url'=>TbfConfig::$UploadUrlPrefix.'/'.$name.'/'.$fileName);
    }
    static function urlToFilePath($url){
        if (!TbfString::HasPrefix($url,TbfConfig::$UploadUrlPrefix)){
            throw new \Exception('input url do not have url prefix');
        }
        return TbfConfig::$UploadPath.TbfString::TrimPrefix($url,TbfConfig::$UploadUrlPrefix);
    }
}